package leetcode;

/**
 * @Author: wqf
 * @Date: 2023/11/20
 * @Description:
 */
public class _0005_回文字符串 {

    public static void main(String[] args) {
        System.out.println(solution("abbacd"));
    }

    public static String solution(String inputStr) {
        if (inputStr.length() <= 1) {
            return inputStr;
        }
        int length = 1;
        int index = 0;
        boolean[][] palindrome = new boolean[inputStr.length()][inputStr.length()];
        for (int i = 0; i < inputStr.length(); i++) {
            palindrome[i][i] = true;
        }

        for (int len = 2; len <= inputStr.length(); len++) {
            for (int i = 0; i < inputStr.length(); i++) {
                int j = i + len - 1;
                if (j >= inputStr.length()) {
                    break;
                }
                if (inputStr.charAt(i) != inputStr.charAt(j)) {
                    palindrome[i][j] = false;
                }
                if (inputStr.charAt(i) == inputStr.charAt(j)) {
                    if (j - i < 3) {
                        palindrome[i][j] = true;
                    } else {
                        palindrome[i][j] = palindrome[i + 1][j - 1];
                    }
                }
                if (palindrome[i][j] && j - i + 1 > length) {
                    length = j - i + 1;
                    index = i;
                }
            }
        }
        return inputStr.substring(index, index + length);
    }
}
